package org.rabbitmq.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: zhs
 * @Date: 2021/6/5 16:49
 * @Description:
 *
 * Routing
 *
 */
public class RoutingProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("192.168.0.199"); //主机
        factory.setPort(5672); //端口
        factory.setVirtualHost("test"); //虚拟机
        factory.setUsername("root"); //用户名
        factory.setPassword("root"); //密码
        factory.setConnectionTimeout(5000);
        //3.获取链接 Connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();
        //5.创建交换机
        /**
         * exchangeDeclare(String exchange, String type, boolean durable, boolean autoDelete,
         *                                        Map<String, Object> arguments)
         *  参数：
         *      1.exchange： 交换机
         *      2.type： 交换机的类型（direct 定向,fanout 广播：发送消息到每一个与之绑定的队列,topic 通配符的方式,headers 参数匹配）
         *      3.durable：  是否持久化
         *      4.autoDelete： 是否删除
         *      5.internal： 内部使用，一般false
         *      6.arguments： 参数
         */
        String exchangeName = "direct_test";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);
        //6.创建队列
        String queueName = "direct_queue_1";
        String queueName2 = "direct_queue_2";
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        //7.绑定队列和交换机
        /**
         * exchangeBind(String destination, String source, String routingKey)
         * 参数：
         *  1.queue：队列名称
         *  2.exchange： 交换机名称
         *  3.routingKey： 路由键，绑定规则
         *      如果交换机的类型是 fanout routingKey 为 ""
         */
        //队列1绑定
        channel.queueBind(queueName,exchangeName,"error");
        //队列2绑定
        channel.queueBind(queueName2,exchangeName,"info");
        channel.queueBind(queueName2,exchangeName,"error");
        channel.queueBind(queueName2,exchangeName,"waring");
        //8.发送消息
        String body = "日志信息:张三调用fingAll方法...日志级别：info...";
        channel.basicPublish(exchangeName,"error",null,body.getBytes());
        //9.释放资源
        channel.close();
        connection.close();
    }
}
